package com.topnav.mc.admin.security.filter.slash;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
/**
 * 说明： 过滤器，把// 变为/
 * @类名: UriFormatFilter
 * <p>
 *
 * 处理URL带双斜杠被权限拦截的问题
 * 在优先最高的拦截里把 多/改写为单/
 * 重新生成 HttpServletRequest， 再走向下一个拦截器
 * </p>
 */
//OncePerRequestFilter，它能够确保在一次请求中只通过一次filter

@Component("uriFormatFilter")
public class UriFormatFilter extends OncePerRequestFilter{

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String uri = request.getRequestURI();
		while(uri.indexOf("//")>-1){
			uri = uri.replace("//","/");
		}
		String newUri = uri;
        // 使用HttpServletRequestWrapper重写Request请求参数
        request = new HttpServletRequestWrapper(request){
            @Override
            public String getRequestURI() {
                return newUri;
            }
        };
        /** 继续走下一个拦截器 */
        filterChain.doFilter(request, response);
	}

}
